package com.jc.service.api.yx163.callback;


import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jc.ds.model.*;
import com.jc.service.xorderreturn.XorderReturnService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jc.cds.model.CustomSupplierProduct;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.framework.enums.Booleans;
import com.jc.framework.enums.Conclusion;
import com.jc.framework.enums.OrderStatus;
import com.jc.framework.enums.SystemUser;
import com.jc.service.api.yx163.YanXuanAdapter;
import com.jc.service.h5.ShopService;
import com.jc.service.jctask.JcTaskService;
import com.jc.service.model.yx.YanXuanResult;
import com.jc.service.order.XorderService;
import com.jc.service.orderproduct.OrderProductsService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.xordermarge.XorderMargeService;
import com.jc.service.xorderprocess.XorderProcessService;

@SuppressWarnings("all")
@Service
public class YanXuanCallBackServiceImpl extends YanXuanAdapter implements YanXuanCallBackService {
	
	private final Logger LOGGER = LoggerFactory.getLogger(YanXuanCallBackServiceImpl.class);
	
	@Autowired
	XorderMargeService xorderMargeService;
	
	@Autowired
	XorderService xorderService;
	
	@Autowired
	OrderProductsService orderProductsService;
	
	@Autowired
	JcTaskService jcTaskService;
	
	@Autowired
	ShopService  shopService;
	@Autowired
	XorderProcessService xorderProcessService;
	
	@Autowired
	SupplierProductService  supplierProductService;

	@Autowired
	private XorderReturnService xorderReturnService;
	

	public YanXuanResult callBack(Map<String, Object> dataMap) {
		YanXuanResult ret = new YanXuanResult();
		LOGGER.error("接收到的网易严选回调参数为  :   {} ",JSONObject.toJSONString(dataMap));
		
		if (dataMap.get("method") == null) {
			throw new BaseServiceException("回调缺少: method参数 ");
		}
		String method = dataMap.get("method").toString();

		switch (method) {
		case "yanxuan.callback.order.cancel":
			// 订单取消回调:修改订单状态,并通知商城
			return YanXuanOrderCancel(dataMap);
		case "yanxuan.notification.inventory.count.check":
			// 渠道SKU库存校准回调 , 修改本地SKU库存，并通知前端商城
			return callback_sku_inventory_change(dataMap);
		case "yanxuan.notification.order.refund.address":
			// 退货地址回调 本次不实现,因为没有确定退货流程
			return returnAddressCallback(dataMap);
		case "yanxuan.callback.item.change":
			// 商品变更回调
			return ret;
		case "yanxuan.notification.order.delivered" :
			return callback_order_express(dataMap);
		case "yanxuan.notification.order.exceptional" :
			//网易严选主动取消订单, 因为发货地，库存，等原因 (这种情况发生较少)
			return ret;
		case"yanxuan.notification.order.refund.reject" :
			//拒绝退货回调
			return refuseReturnCallback(dataMap);
		case "yanxuan.notification.order.refund.express.confirm" :
			//退货包裹确认收货回调
			return returnPackageConfirmationReceiptCallback(dataMap);
		case "yanxuan.notification.order.refund.system.cancel" :
			//系统取消退货回调
			return systemCancelsReturnCallback(dataMap);
			case "其它":
			return ret;
		}
		return null;
		//LOGGER.error("接收到网易严选回调参数 : {}", "");
	}
	
	
	@Transactional
	public YanXuanResult callback_canel_order() {
		return null;
	}
	
	@Transactional
	public YanXuanResult callback_order_express(Map<String, Object> dataMaps) {
		
		
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		if(dataMaps.get("orderPackage") == null) {
			throw new BaseServiceException("订单运单号回调参数错误, 缺少业务数据字段 :  orderPackage" );
		}
		JSONObject dataMap = JSON.parseObject(dataMaps.get("orderPackage").toString());
		//更新OMS系统中订单状态 , 同时填进去 物流公司和运单号
		String orderId = (String)dataMap.get("orderId");
		if(StringUtils.isBlank(orderId)) 
		{
			ret.setCode(99999);
			ret.setMessage(" orderId 这个参数不允许为空 !");
			return ret;
		}
		
		//查看有没有多次推送的记录，找到最后一次推送记录,关联到原订单号
		XorderMarge xorderMargeByChannelOrder = xorderMargeService.getXorderMargeByChannelOrderId(orderId);
		String channelOrderId = "";
		if(xorderMargeByChannelOrder == null) { //无重复推送记录
			channelOrderId = orderId;
		}else { //有记录
			channelOrderId = xorderMargeByChannelOrder.getChannelOrderId();
		}
		if(dataMap.get("expressDetailInfos") == null) {
			ret.setCode(99999);
			ret.setMessage(" 订单运单号回调参数错误, 缺少业务数据字段 :  expressDetailInfos !");
			return ret;
		}
		//String arrayStr = (String)dataMap.("expressDetailInfos");
		String arrayStr = dataMap.getString("expressDetailInfos");
		Map<String,Map<String,Object>> expressMap = getOrderExpress(arrayStr);
		
		//查看有没有合并订单的记录
		List<Xorder> orderList = new ArrayList<Xorder>();
		List<XorderMarge> childOrderList = xorderMargeService.getChildOrderList(channelOrderId);
		String parentOrderId = null;
		if(CollectionUtils.isEmpty(childOrderList)) {//无合单记录
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(channelOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = xorderService.queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( channelOrderId +  " 订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			orderList = olist;
		}else {//有合单记录
			parentOrderId = channelOrderId;
			for(XorderMarge mg : childOrderList) {
				Long childOrderId = mg.getOrderId();
				orderList.add(xorderService.queryById(childOrderId));
			}
		}
		
		
		// 现在每个子订单只有一个产品, 根据SKUID 比较后，更新子订单物流单号.
		String express_codes = "";
		for(Xorder o : orderList) {
			
			if(StringUtils.equals(o.getOrderStatus(),OrderStatus.outstorage.getName())) {
				//该条订单已出库跳过
				continue;
			}
			OrderProducts op = new OrderProducts();
		    op.setOrderId(o.getId());
			List<OrderProducts> oplist = orderProductsService.queryAll(op);
			if(CollectionUtils.isNotEmpty(oplist)) {
				
				String suppliper_product_id = oplist.get(0).getSupplierProductId();
				Map<String,Object> map = expressMap.get(suppliper_product_id);
				String expressNo = (String)map.get("expressNo");
				String expressCompany = (String)map.get("expressCompany");
				express_codes = express_codes  + expressNo + ",";
				o.setExpressNo(expressNo);
				o.setExpressName(expressCompany);
				o.setOrderStatus(OrderStatus.outstorage.getName());
				o.setUpdateTime(new Date());
				xorderService.modify(o, false);
				//推送商城
				String code = shopService.pushOrder(o.getChannelOrderId());
				if(code != null && StringUtils.equals("0", code)) {
					xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城成功", SystemUser.ADMIN.getName(), o.getId());
				}else {
					xorderProcessService.addXorderProcess(o.getChannelOrderId(), "订单推送商城过程中发生错误,处理失败", SystemUser.ADMIN.getName(), o.getId());
				}
			}
		}
		
		if(StringUtils.isNotBlank(parentOrderId)) { //更新父订单的状态和运单号
			Xorder queryOrder = new Xorder();
			queryOrder.setChannelOrderId(parentOrderId);
			queryOrder.setIsDelete(Booleans.FALSE.getName());
			List<Xorder> olist = xorderService.queryAll(queryOrder);
			if(CollectionUtils.isEmpty(olist)) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单不存在,无法出库");
				return ret;
			}
			if(olist.size() > 1) {
				ret.setCode(99999);
				ret.setMessage( parentOrderId +  " 父订单在订单表存在两条以上记录,无法出库");
				return ret;
			}
			Xorder updateOrder = olist.get(0);
			updateOrder.setOrderStatus(OrderStatus.outstorage.getName());
			updateOrder.setExpressNo(express_codes);
			updateOrder.setUpdateTime(new Date());
			xorderService.modify(updateOrder, false);
		}
		return ret;
	}
	
	
	
	
	
	public Map<String ,Map<String,Object>> getOrderExpress(String expressDetailInfos){
		Map<String ,Map<String,Object>> maps = new HashMap<String ,Map<String,Object>>();
		JSONArray objectArray = JSON.parseArray(expressDetailInfos);
		for(int i = 0 ; objectArray != null && i < objectArray.size() ; i++ ) {
			
			JSONObject expressObject = objectArray.getJSONObject(i);
			String expressCompany = null;
			String expressNo = null;
			if(objectArray != null) {
				expressNo = expressObject.getString("expressNo");
				expressCompany = expressObject.getString("expressCompany");	
			}
			Map<String,Object> expressMap = new HashMap<String, Object>();
			expressMap.put("expressNo", expressNo);
			expressMap.put("expressCompany", expressCompany);
			
			if(StringUtils.isNotBlank(expressObject.getString("skus"))) {
				JSONArray skuArray = JSON.parseArray(expressObject.getString("skus"));
				for(int k = 0 ; skuArray != null && k < skuArray.size() ; k++) {
					JSONObject skuObject = skuArray.getJSONObject(k);
					String skuid = skuObject.getString("skuId");
					maps.put(skuid, expressMap);
				}
			}
		}
		
		return maps;
	}
	
	
	
	@Transactional
	public YanXuanResult callback_sku_inventory_change(Map<String, Object> dataMap) {
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		if(dataMap.get("reopenSkus") == null) {
			throw new BaseServiceException("库存变更回调参数错误, 缺少业务数据字段 :  reopenSkus" );
		}
		JSONArray skulist = null;
		String businessData = (String)dataMap.get("reopenSkus");
		try {
			skulist = JSONArray.parseArray(businessData);
		}catch (Exception e) {
			throw new BaseServiceException("库存变更回调参数错误,  reopenSkus 这个字段格式不为数组");
		}
		
		for(int i = 0 ; skulist != null && i < skulist.size() ; i++) {
			JSONObject skuChangeObject = skulist.getJSONObject(i);
			String skuId = skuChangeObject.getString("skuId");
			int    inventroy = skuChangeObject.getInteger("inventory");
			//更改本地表中的库存
			Map<String,Object> _objectMap = new HashMap<String,Object>();
			_objectMap.put("productId", skuId);
			List<CustomSupplierProduct> _list = supplierProductService.selectProductBySupplier(_objectMap);
			if(CollectionUtils.isEmpty(_list)) {
				ret.setCode(9999);
				ret.setMessage(skuId + "这个SKUID在该严选渠道下面不存在");
				return ret;
			}
			if(_list.size() > 1) {
				ret.setCode(9999);
				ret.setMessage(skuId + "这个SKUID在该严选渠道下面存在多条记录,无法更新库存");
				return ret;
			}
			SupplierProduct updateSupplierProduct = new SupplierProduct();
			updateSupplierProduct.setId(_list.get(0).getId());
			updateSupplierProduct.setInventoryNum(Integer.valueOf(inventroy));
			supplierProductService.modify(updateSupplierProduct, false);
			//推送商城一次 skuCode 为OMS系统表中 supplier_product id 主键字段.
			shopService.pushInventory(_list.get(0).getId(), ""+inventroy);
			
		}
		
		
		return ret;
	}


	/**
	 * 严选取消回调
	 * */
	public YanXuanResult YanXuanOrderCancel(Map<String, Object> dataMap){
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());

		//判断订单是否取消成功
		Map<String, Object> orderCancelResult = JSONObject.parseObject(dataMap.get("orderCancelResult").toString(), Map.class);
		String cancelStatus = orderCancelResult.get("cancelStatus").toString();
		String orderId = orderCancelResult.get("orderId").toString();
		List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
			setChannelOrderId(orderId);
		}});
		if (CollectionUtils.isEmpty(xorders) || xorders.size() > 1){
			System.out.println("==============系统存在多个订单");
			return ret;
		}
		Xorder xorder = xorders.get(0);

		//查询申请单
		List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
			setOrderId(xorder.getId());
		}});
		XorderReturn xorderReturn = xorderReturns.get(0);
		if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() >1 ){
			throw new BaseServiceException("申请单存在多个 . orderId " +xorder.getId());
		}
		Xorder upXorder = new Xorder();
		upXorder.setId(xorder.getId());
		if ("0".equals(cancelStatus)){
			upXorder.setOrderStatus(OrderStatus.NO_RETURN_ALLOWED.getName());
			xorderReturn.setStatus("11");
		}else if("1".equals(cancelStatus)){
			upXorder.setOrderStatus(OrderStatus.RETURNED.getName());
			xorderReturn.setStatus("8");
		}else if("2".equals(cancelStatus)){
			upXorder.setOrderStatus(OrderStatus.wait_auditing.getName());
			xorderReturn.setStatus("9");
		}
		xorderService.modify(upXorder,false);
		xorderReturnService.modify(xorderReturn,false);
		return ret;
	}
	/**
	 * 退货地址回调
	 * **/
	public YanXuanResult returnAddressCallback(Map<String,Object> dataMap){
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		System.out.println("==============退货地址回调 请求参数: "+dataMap);
		Map<String,Object> refundAddress = JSONObject.parseObject(dataMap.get("refundAddress").toString(), Map.class);
		String orderId = refundAddress.get("orderId").toString();
		List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
			setChannelOrderId(orderId);
		}});
		if (CollectionUtils.isEmpty(xorders) || xorders.size() > 1){
			throw new BaseServiceException("订单存在多个 或者订单不存在  渠道Id "+ orderId);
		}
		Xorder xorder = xorders.get(0);
		List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
			setOrderId(xorder.getId());
		}});
		if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() > 1){
			throw new BaseServiceException("申请单存在多个 或者申请单不存在  渠道Id "+ orderId);
		}
		XorderReturn xorderReturn = xorderReturns.get(0);
		xorderReturn.setIsPay(refundAddress.get("type").toString());
		xorderReturn.setStatus("2");
		xorderReturnService.modify(xorderReturn,false);

		xorder.setOrderStatus(OrderStatus.RETURN_THE_GOODS.getName());
		xorderService.modify(xorder,false);
		return ret;
	}

	/**
	 * 严选拒绝退货 .
	 * */
	public YanXuanResult refuseReturnCallback (Map<String,Object> dataMap){
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		System.out.println("==============严选拒绝退货回调 请求参数: "+dataMap);
		Map<String,Object> rejectInfo = JSONObject.parseObject(dataMap.get("rejectInfo").toString(), Map.class);
		String orderId = rejectInfo.get("orderId").toString();
		List<Xorder> xorders = xorderService.queryAll(new Xorder() {{
			setChannelOrderId(orderId);
		}});
		if (CollectionUtils.isEmpty(xorders) || xorders.size() > 1){
			throw new BaseServiceException("订单存在多个 或者订单不存在  渠道Id "+ orderId);
		}
		Xorder xorder = xorders.get(0);
		List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
			setOrderId(xorder.getId());
		}});
		if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() > 1){
			throw new BaseServiceException("申请单存在多个 或者申请单不存在  渠道Id "+ orderId);
		}
		XorderReturn xorderReturn = xorderReturns.get(0);

		xorder.setOrderStatus(OrderStatus.NO_RETURN_ALLOWED.getName());
		xorderService.modify(xorder,false);
		xorderReturn.setStatus("11");
		xorderReturn.setDenyReason(rejectInfo.get("rejectReason").toString());
		xorderReturnService.modify(xorderReturn,false);
		return ret;
	}


	/**
	 * 严选确认收货,待退款
	 * **/
	public YanXuanResult returnPackageConfirmationReceiptCallback(Map<String,Object> dataMap){
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		System.out.println("==============严选确认收货,待退款回调 请求参数: "+dataMap);
		Map<String,Object> expressConfirm = JSONObject.parseObject(dataMap.get("expressConfirm").toString(), Map.class);

		String applyId = expressConfirm.get("applyId").toString();

		List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
			setReturnFromId(applyId);
		}});
		if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() > 1){
			throw new BaseServiceException("申请单存在多个 或者申请单不存在  申请单Id"+ applyId);
		}
		XorderReturn xorderReturn = xorderReturns.get(0);
		xorderReturn.setStatus("4");
		xorderReturnService.modify(xorderReturn,false);

		Xorder xorder = xorderService.queryById(xorderReturn.getOrderId());
		xorder.setOrderStatus(OrderStatus.PENDING_REFUND.getName());
		xorderService.modify(xorder,false);
		return ret;
	}


	/**
	 *严选系统取消订单
	 * */
	public YanXuanResult systemCancelsReturnCallback(Map<String,Object> dataMap){
		YanXuanResult ret = new YanXuanResult();
		ret.setMessage(Conclusion.OK.getDesc());
		System.out.println("==============严选系统取消订单回调 请求参数: "+dataMap);
		Map<String,Object> expressConfirm = JSONObject.parseObject(dataMap.get("systemCancel").toString(), Map.class);

		String applyId = expressConfirm.get("applyId").toString();

		List<XorderReturn> xorderReturns = xorderReturnService.queryAll(new XorderReturn() {{
			setReturnFromId(applyId);
		}});
		if (CollectionUtils.isEmpty(xorderReturns) || xorderReturns.size() > 1){
			throw new BaseServiceException("申请单存在多个 或者申请单不存在  申请单Id"+ applyId);
		}
		XorderReturn xorderReturn = xorderReturns.get(0);
		xorderReturn.setStatus("7");
		xorderReturnService.modify(xorderReturn,false);

		Xorder xorder = xorderService.queryById(xorderReturn.getId());
		xorder.setOrderStatus(OrderStatus.RETURN_ORDER_INVALID.getName());
		xorderService.modify(xorder,false);
		return ret;
	}
}
